package com.baijia.tianxiao.connect.daemon;

import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.WebSocketSession;

import com.baijia.tianxiao.connect.config.Constants;

/**
 * @author leiruiqi
 *
 *	守护线程检查超时
 *
 *	1、因为容器自己也有标准配置可以设置超时时间，所以个守护线程不是必要。
 *	2、但是考虑到可以增加其它检测，仍然让这个线程启动，并且这里设置的超时时间间隔需要小于等于容器配置的超时时间
 *
 */
public class KeepLiveCheckThread extends Thread{

	private static Logger logger = LoggerFactory.getLogger(KeepLiveCheckThread.class); 
	
	ConcurrentHashMap<String,WebSocketSession> sessionMap;
	
	
	public KeepLiveCheckThread(ConcurrentHashMap<String,WebSocketSession> sessionMap) {
		this.sessionMap = sessionMap;
		this.setDaemon(true);
	}	
	@Override
	public void run() {
		
		while(true){
			try {
				//一分钟启动一次轮训
				Thread.sleep(60000);
			} catch (InterruptedException e1) {
				logger.error("",e1);
			}
			logger.info("start check keeplive");
			long now = System.currentTimeMillis();
			for(WebSocketSession session:sessionMap.values()){
				Long lastTime = (Long)session.getAttributes().get(Constants.LAST_MSG_TIME);
				//150秒的超时限制
				if(now-lastTime>1000*150){
					try {
						session.close(CloseStatus.SESSION_NOT_RELIABLE.withReason("timeout"));	
						logger.info("close session for timeout sessionid="+session.getAttributes().get("websocket_username"));
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		}
	}

	
}
